<?php
/*
Plugin Name: WP cr mobile
Description: Creates branded mobile review sites for companies where customers can instantly post reviews. Companies can moderate reviews and setup publishing thresholds. The reviews can be displayed via a shortcode or a widget.
License: GPLv2 or later

*/

/** Load all of the necessary class files for the plugin */
spl_autoload_register('CRMobile::autoload');

/**
 * Init Singleton Class for the plugin.
 *
 * @package WP cr mobile
 */
class CRMobile
{
    private static $instance = false;
    const MIN_PHP_VERSION    = '5.2.4';
    const MIN_WP_VERSION     = '3.5';
    const OPTION_DB_KEY      = 'wp_cr_mobile';
    const PLUGIN_SLUG        = 'wp-cr-mobile/wp-cr-mobile.php';
    const FILE               = __FILE__;

    /**
     * Singleton class
     */
    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Constructor.
     * Initializes the plugin by setting localization, filters, and
     * administration functions.
     */
    private function __construct()
    {
        if (!$this->testHost()) {
            return;
        }
        if (!$this->testPermalinks()) {
            return;
        }

        register_uninstall_hook(__FILE__, array(__CLASS__, 'uninstall'));
        add_action('init', array($this, 'textDomain'));

        add_action(
            'widgets_init',
            create_function('', 'register_widget("CRMobile_Widget");')
        );

        $this->admin      = new CRMobile_Admin;
        $mobileSite = new CRMobile_MobileSite;
        $shortcode  = new CRMobile_Shortcode;
        $theme = CRMobile_Theme::getInstance();

        // $this->uninstall();
        // $this->install();
    }

    /**
     * PSR-0 compliant autoloader to load classes as needed.
     *
     * @since  1.7
     *
     * @param  string  $classname  The name of the class
     * @return null    Return early if the class name does not start with the
     *                 correct prefix
     */
    public static function autoload($className)
    {
        if ('CRMobile' !== mb_substr($className, 0, 16)) {
            return;
        }
        $className = ltrim($className, '\\');
        $fileName  = '';
        $namespace = '';
        if ($lastNsPos = strrpos($className, '\\')) {
            $namespace = substr($className, 0, $lastNsPos);
            $className = substr($className, $lastNsPos + 1);
            $fileName  = str_replace('\\', DIRECTORY_SEPARATOR, $namespace);
            $fileName .= DIRECTORY_SEPARATOR;
        }
        $fileName .= str_replace('_', DIRECTORY_SEPARATOR, 'lib_'.$className);
        $fileName .='.php';

        require $fileName;
    }

    /**
     * Loads the plugin text domain for translation
     */
    public function textDomain()
    {
        $domain = 'wp-cr-mobile';
        $locale = apply_filters('plugin_locale', get_locale(), $domain);
        load_textdomain(
            $domain,
            WP_LANG_DIR.'/'.$domain.'/'.$domain.'-'.$locale.'.mo'
        );
        load_plugin_textdomain(
            $domain,
            false,
            dirname(plugin_basename(__FILE__)).'/lang/'
        );
    }

    /**
     * When the plugin is activated.
     */
    public static function install()
    {
        // Add roles and capabilites used by the plugin
        add_role(
            'wp_crmobile _moderator',
            'CMob Moderator',
            array(
                'read' => true,
                'can_access_wp_cr_mobile' => true
            )
        );
        $role = get_role('administrator');
        $role->add_cap('can_access_wp_cr_mobile');

        // Setup database tables
        $db = new CRMobile_DatabaseSetup;
        $db->createTables();
    }

    /**
     * When the plugin is uninstalled.
     */
    public function uninstall()
    {
        // Remove roles and capabilites created by the plugin
        $role = get_role('administrator');
        $role->remove_cap('can_access_wp_cr_mobile');
        remove_role('wp_crmobile _moderator');

        // Remove database tables
        $db = new CRMobile_DatabaseSetup;
        $db->dropTables();

        // Delete options
        delete_option(self::OPTION_DB_KEY);
    }


    // -------------------------------------------------------------------------
    // Environment Checks
    // -------------------------------------------------------------------------

    /**
     * Checks so WordPress is properly configured for this plugin.
     */
    private function testPermalinks()
    {
        if (!get_option('permalink_structure')) {
            add_action(
                'admin_notices',
                array(&$this, 'permalinkNotice')
            );
            return false;
        }
        return true;
    }

    public function permalinkNotice()
    {
        echo CRMobile_View::render(
            plugin_dir_path(__FILE__).'views/notice_permalink.php'
        );
    }

    /**
     * Checks PHP and WordPress versions.
     */
    private function testHost()
    {
        // Check if PHP is too old
        if (version_compare(PHP_VERSION, self::MIN_PHP_VERSION, '<')) {
            // Display notice
            add_action('admin_notices', array(&$this, 'phpVersionError'));
            return false;
        }

        // Check if WordPress is too old
        global $wp_version;
        if (version_compare($wp_version, self::MIN_WP_VERSION, '<')) {
            add_action('admin_notices', array(&$this, 'wpVersionError'));
            return false;
        }
        return true;
    }

    /**
     * Displays a warning when installed on an old PHP version.
     */
    public function phpVersionError()
    {
        echo '<div class="error"><p><strong>';
        printf(
            'Error: WP cr mobile requires PHP version %1$s or greater.<br/>'.
            'Your installed PHP version: %2$s',
            self::MIN_PHP_VERSION,
            PHP_VERSION
        );
        echo '</strong></p></div>';
    }

    /**
     * Displays a warning when installed in an old Wordpress version.
     */
    public function wpVersionError()
    {
        echo '<div class="error"><p><strong>';
        printf(
            'Error: WP cr mobile requires WordPress version %s or greater.',
            self::MIN_WP_VERSION
        );
        echo '</strong></p></div>';
    }
}

add_action('plugins_loaded', array('CRMobile', 'getInstance'));
register_activation_hook(__FILE__, array('CRMobile', 'install'));
